package com.sumainfor.zuul.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.ParentDeptVo;
import com.sumainfor.common.util.Constant;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.zuul.dao.SysMenuDao;
import com.sumainfor.zuul.dao.SysRoleDao;
import com.sumainfor.zuul.dao.SysUserDao;
import com.sumainfor.zuul.dao.SysUserTokenDao;
import com.sumainfor.zuul.entity.*;
import com.sumainfor.zuul.service.ShiroService;
import com.sumainfor.zuul.service.SysDeptService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Log4j2
public class ShiroServiceImpl implements ShiroService {

    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserTokenDao sysUserTokenDao;

    @Autowired
    private SysRoleDao SysRoleDao;

    @Autowired
    private SysDeptService sysDeptService;

    @Override
    public Set<String> getUserPermissions(Integer userId) {
        List<String> permsList;
        List<Integer> list = Arrays.asList(Constant.SUPER_ADMIN2);
        //系统管理员，拥有最高权限
        if (userId == Constant.SUPER_ADMIN) {
            List<SysMenuEntity> menuList = sysMenuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for (SysMenuEntity menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else if (list.contains(Integer.valueOf(userId + ""))) {
            List<SysMenuEntity> menuList = sysMenuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for (SysMenuEntity menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = sysUserDao.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String token) {
        return sysUserTokenDao.queryByToken(token);
    }

    @Override
    public SysUserEntity queryUser(Integer userId) {
        SysUserEntity userEntity = sysUserDao.getUserEntityById(userId);

        List<Integer> roleIdList = Lists.newArrayList();
        userEntity.setRoleIdList(roleIdList);
        //查询出这个用户的上级部门的所有上级部门信息
        if (userEntity != null) {
            if (userEntity.getDeptId() != null && userEntity.getDeptId() != 0) {
                SysDeptEntity entity = sysDeptService.selectById(userEntity.getDeptId());
                if (entity == null) {
                    return userEntity;
                }
                ParentDeptVo root = new ParentDeptVo();
                root.setDeptId(entity.getDeptId());
                root.setName(entity.getName());
                root.setType(entity.getType());
                if (entity.getParentId() != 0) {
                    returnsDept(root, userEntity);
                }
                userEntity.setParentDeptVo(root.getParentDeptVo());
            }

            //查询下级部门列表
            Set<Integer> bottomList = Sets.newHashSet();
            eachBottomDeptId(bottomList, userEntity.getDeptId());
            userEntity.setBottomDeptList(bottomList);
        }
        //根据用户编号获取当前用户绑定的角色信息
        if (userEntity != null) {
            if (userEntity.getUserId() != null && userEntity.getUserId() != 0) {
                List<SysUserRoleVo> roleList = new ArrayList<SysUserRoleVo>();
                List<Map<String, Object>> userRoleVo = SysRoleDao.getUserRoleEntutyByUserId(userEntity.getUserId());
                log.info("userRoleVo------" + userRoleVo);
                if (userRoleVo.size() > 0) {
                    for (Map<String, Object> map : userRoleVo) {
                        SysUserRoleVo userRole = new SysUserRoleVo();
                        userRole.setRoleId(Integer.valueOf(map.get("RoleId").toString()));
                        if (FieldCheckUtil.isMapFieldNotNull(map, new String[]{"Remark"})) {
                            userRole.setRemark(map.get("Remark").toString());
                        }
                        userRole.setRoleName(map.get("RoleName").toString());
                        roleList.add(userRole);
                        roleIdList.add(MapUtils.getInteger(map, "RoleId"));
                    }
                }

                userEntity.setRoleList(roleList);
            }
        }
        //根据用户编号获取当前用户绑定的微信资料
        if (userEntity != null) {
            if (userEntity.getUserId() != null && userEntity.getUserId() != 0) {
                SysUserWxEntity UserWx = sysUserDao.getUserWxEntityByUserId(userEntity.getUserId());
                if (UserWx == null) {
                    return userEntity;
                }
                userEntity.setUserWeChat(UserWx);
            }
        }
        return userEntity;
    }


    public Set<Integer> eachBottomDeptId(Set<Integer> bottomList, Integer id) {
        List<SysDeptEntity> deptList = sysDeptService.getChildDeptByParentId(id);

        for (int i = 0; i < deptList.size(); i++) {
            SysDeptEntity entity = deptList.get(i);
            bottomList.add(entity.getDeptId());
        }

        for (int i = 0; i < deptList.size(); i++) {
            eachBottomDeptId(bottomList, deptList.get(i).getDeptId());
        }
        return bottomList;
    }


    /**
     * 递归部门
     *
     * @param vo
     * @return
     */
    public ParentDeptVo returnsDept(ParentDeptVo vo, SysUserEntity userEntity) {
        SysDeptEntity entity = sysDeptService.getDeptParentByDeptId(vo.getDeptId());
        if (entity == null) {
            return vo;
        }
        ParentDeptVo child = new ParentDeptVo();
        child.setDeptId(entity.getDeptId());
        child.setName(entity.getName());
        child.setType(entity.getType());

        if (Constants.AuthDeptType.Impl.isServiceCenter(child.getType())) {
            //递归获得 这个服务中心部门下所有的子部门ID
            Set<Integer> bottomList = Sets.newHashSet();
            eachBottomDeptId(bottomList, child.getDeptId());
            userEntity.setCenterServiceChild(bottomList);
        }
        vo.setParentDeptVo(child);

        if (entity.getParentId() != 0) {
            returnsDept(vo, userEntity);
        } else {
            return child;
        }
        return vo;
    }

    /**
     * 删除过期的Token
     */
    @Override
    public void deletePastToken() {
        sysUserTokenDao.deletePactToken();
    }

}
